import React, { forwardRef, useEffect, useState } from 'react'
import { Select } from "antd";
import { getWarehouseSelection, setSelectedWarehouse } from "@sagas/warehouse/warehouseManagement";
import { useSelector, useDispatch } from "react-redux";

export const WarehouseSelect = props => {
    const { value, onChange, width } = props
    const [id, setId] = useState(value)
    const dispatch = useDispatch()
    const { selectedWarehouse, warehouseSelection } = useSelector(state => state.warehouseManagement)

    useEffect(() => {
        if (id) {
            dispatch(getWarehouseSelection({}, () => {
                dispatch(setSelectedWarehouse(id))
            }))
        } else {
            dispatch(getWarehouseSelection({}, (res) => {
                if (selectedWarehouse) {
                    setId(selectedWarehouse)
                    dispatch(setSelectedWarehouse(selectedWarehouse))
                    onChange(selectedWarehouse)
                } else if (res.warehouses && !selectedWarehouse) {
                    dispatch(setSelectedWarehouse(res.warehouses[0].id))
                    setId(res.warehouses[0].id)
                    onChange(res.warehouses[0].id)
                } else if (!res.warehouses || res.warehouses.length === 0) {
                    dispatch(setSelectedWarehouse(''))
                }
            }))
        }
    }, [])

    const handleValueChange = value => {
        setId(value)
        dispatch(setSelectedWarehouse(value))
        onChange(value)
    }

    return (
        <>
            <Select
                style={{ width: width || '140px' }}
                value={id}
                onChange={handleValueChange}
            >
                {warehouseSelection.map(warehouse => (
                    <Select.Option key={warehouse.id} value={warehouse.id}>{warehouse.name}</Select.Option>
                ))}
            </Select>
        </>
    )
}